package org.jeecg.glr.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.net.ftp.FTPClient;
import org.jeecg.common.util.SysUtil;
import org.jeecg.glr.entity.GlrRadio;
import org.jeecg.glr.entity.GlrRadioServer;
import org.jeecg.glr.entity.GlrRadioTask;
import org.jeecg.glr.mapper.GlrRadioMapper;
import org.jeecg.glr.mapper.GlrRadioServerMapper;
import org.jeecg.glr.mapper.GlrRadioTaskMapper;
import org.jeecg.glr.service.IGlrRadioServerService;
import org.jeecg.glr.util.FtpUtil;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.HttpRequestUtil;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

import static org.jeecg.glr.util.GLRConstant.*;

/**
 * @Description: 音柱服务器管理
 * @Author: jeecg-boot
 * @Date:   2020-02-11
 * @Version: V1.0
 */
@Service
public class GlrRadioServerServiceImpl extends ServiceImpl<GlrRadioServerMapper, GlrRadioServer> implements IGlrRadioServerService {

    @Value("${glr.url.radio_teriocontrol}")
    private  String radio_teriocontrol;

    @Autowired
    private GlrRadioServerMapper glrRadioServerMapper;

    @Autowired
    private GlrRadioMapper glrRadioMapper;

    @Autowired
    private GlrRadioTaskMapper glrRadioTaskMapper;


    public GlrRadio updateGlrRadioServerCodeByCompanyCode(GlrRadio glrRadio){
        if (glrRadio!=null){
            if (StringUtil.isNotEmpty(glrRadio.getCompanyCode())){
                if (COMPANY_CODE_RATTOP.equals(glrRadio.getCompanyCode())){
                    glrRadio.setRadioServerCode(SERVER_CODE_RATTOP);
                }
            }
        }
        return glrRadio;
    }

    public GlrRadioServer doGetByPropertyName(String propertyName, String value){
        QueryWrapper<GlrRadioServer> queryWrapper = new QueryWrapper<GlrRadioServer>();
        queryWrapper.eq(propertyName, value);
        GlrRadioServer glrRadioServer=super.getOne(queryWrapper);
        return glrRadioServer;
    }

    public String getRattopSessionId(GlrRadioServer entity) throws Exception{
        String stSessionId = "";
        try{

            String stIp = entity.getIp();
            String stPort = entity.getPort();
            String stUserName = entity.getUserName();
            String stPassword = entity.getPassword();
            String stJSessionID = entity.getSessionId();

            String localhost = stIp + ":" + stPort;
            String function = "";

            //需要调用登录接口
            boolean bNeedLogin = false;
            if (StringUtil.isEmpty(stJSessionID)) {
                bNeedLogin = true;
            }else{
                function = "getGroups";
                String url = IPCAST_FUNCTION_URL.replaceAll("localhost", localhost).replaceAll("function",
                        function);
                url = url + ";JSESSIONID=" + stJSessionID;
                JSONObject jsonParam = new JSONObject();
                com.alibaba.fastjson.JSONObject json = HttpRequestUtil.httpRequest(url, "POST", jsonParam.toString());
                if (json == null) {
                    bNeedLogin = true;
                }else {
                    //System.out.println(json.toString());
                    Integer IRet = json.getInteger("Ret");
                    if (IRet != 0) {
                        bNeedLogin = true;
                    } else {
                        bNeedLogin = false;
                    }
                }
            }
            if (bNeedLogin) {
                function = "login";
                String url = IPCAST_FUNCTION_URL.replaceAll("localhost", localhost).replaceAll("function",
                        function);
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("User", stUserName);
                jsonParam.put("Passwd", stPassword);
                com.alibaba.fastjson.JSONObject json = HttpRequestUtil.httpRequest(url, "POST", jsonParam.toString());
                if (json == null) {
                    throw new Exception("error3");
                }else {
                    //System.out.println(json.toString());
                    Integer IRet = json.getInteger("Ret");
                    if (IRet != 0) {
                        throw new Exception("error4");
                    } else {
                        GlrRadioServer entity1 = glrRadioServerMapper.selectById(entity.getId());
                        entity1.setSessionId(json.getString("JSessionID"));
                        glrRadioServerMapper.updateById(entity1);
                        entity.setSessionId(entity1.getSessionId());
                    }
                }
            }
        }catch (Exception ex){
            //System.out.println(ex.getMessage());
            GlrRadioServer entity1 = glrRadioServerMapper.selectById(entity.getId());
            if (StringUtil.isNotEmpty(entity1.getSessionId())) {
                entity1.setSessionId("");
                glrRadioServerMapper.updateById(entity1);
                entity.setSessionId(entity1.getSessionId());
            }
        }

        //entity = glrRadioServerMapper.selectById(entity.getId());
        stSessionId = entity.getSessionId();
        return stSessionId;
    }

    public String getRattopSessionId(String glrRadioServerId) throws Exception{
        GlrRadioServer entity = glrRadioServerMapper.selectById(glrRadioServerId);
        return getRattopSessionId(entity);
    }

    public void doUpdateRattopTerminalInfo(String ids) throws Exception{
        String str[] = ids.split(",");
        for (String id : str) {
            GlrRadio domain = glrRadioMapper.selectById(id);
            doUpdateRattopTerminalInfo(domain);
        }
    }

    public void doUpdateRattopTerminalInfo(String ids,String stJSessionID) throws Exception{
        String str[] = ids.split(",");
        for (String id : str) {
            GlrRadio domain = glrRadioMapper.selectById(id);
            doUpdateRattopTerminalInfo(domain);
        }
    }

    public com.alibaba.fastjson.JSONObject IPCAST_FUNCTION(GlrRadioServer entity, String function, JSONObject jsonParam, boolean bNeedSession) throws Exception {
        String stJSessionID = getRattopSessionId(entity);
        return IPCAST_FUNCTION(entity,function,jsonParam,bNeedSession,stJSessionID);
    }

    public com.alibaba.fastjson.JSONObject IPCAST_FUNCTION(GlrRadioServer entity,String function, JSONObject jsonParam, boolean bNeedSession,String stJSessionID) throws Exception {
        String stIp = entity.getIp();
        String stPort = entity.getPort();
        if (StringUtil.isEmpty(stJSessionID)) throw new Exception("不能联上音柱服务器！");
        String localhost = stIp + ":" + stPort;
        String url = IPCAST_FUNCTION_URL.replaceAll("localhost", localhost).replaceAll("function",
                function);
        if (bNeedSession) url = url + ";JSESSIONID=" + stJSessionID;
       JSONObject json = HttpRequestUtil.httpRequest(url, "POST", jsonParam.toString());
        //{"Ret":1,"Remark":"Failed"}
        if (json!=null&&json.getInteger("Ret") == 0) {
        } else {
            //System.out.println(json.toString());
            throw new Exception("接口失败!");
        }
        return json;
    }


    public int volumeConversionPerToRattop(int valuePer){
        //int iReturn =(valuePer/PER_CENT_MAX)*PER_CENT_MAX_RATTOP;
        int iReturn =new Double(Math.ceil((((double)valuePer)/PER_CENT_MAX)*PER_CENT_MAX_RATTOP)).intValue();
        return iReturn;
    }
    public int volumeConversionRattopToPer(int valueRattop){
        //int iReturn =(valueRattop/PER_CENT_MAX_RATTOP)*PER_CENT_MAX;
        int iReturn =new Double(Math.ceil((((double)valueRattop)/PER_CENT_MAX_RATTOP)*PER_CENT_MAX)).intValue();
        return iReturn;
    }

    public void doUpdateRattopTerminalInfo(GlrRadio glrRadio) throws Exception{
        GlrRadioServer glrRadioServer = glrRadio.getGlrRadioServer();
        String stJSessionID = getRattopSessionId(glrRadioServer);
        doUpdateRattopTerminalInfo(glrRadio,stJSessionID);
    }

    public void doUpdateRattopTerminalInfo(GlrRadio glrRadio,String stJSessionID) throws Exception{
        glrRadio.setRadioStatus(-1);
        String stId=glrRadio.getId();
        String stRadioServerCode = glrRadio.getRadioServerCode();
        if (StringUtil.isNotEmpty(stId)&& StringUtil.isNotEmpty(stRadioServerCode) && glrRadio.getGlrRadioServer() == null) {
            GlrRadioServer glrRadioServer=doGetByPropertyName("code", stRadioServerCode);
            glrRadio.setGlrRadioServer(glrRadioServer);
        }
        GlrRadioServer glrRadioServer = glrRadio.getGlrRadioServer();
        if (glrRadioServer != null) {
            JSONObject jsonParam = new JSONObject();

            //jsonParam.put("TermIDs", "[" + glrRadio.getRadioId() + "]");
            JSONArray j=new JSONArray();
            j.add(Long.parseLong(glrRadio.getRadioId()));
            jsonParam.put("TermIDs",j);

            com.alibaba.fastjson.JSONObject jsonReturn = IPCAST_FUNCTION(glrRadioServer, "getTermState", jsonParam, true,stJSessionID);
            //Status-1-离线 0-空闲>0-工作中
            //{"Ret":0,"Terms":[
            //{"Status":-1,"Vol":2,"Number":1,"WorkStatus":0,"IP":"26.117.13.188","CallStatus":0,"ID":1,"Name":"glr20190617001","Sid":-1},
            //{"Status":-1,"Vol":2,"Number":2,"WorkStatus":0,"IP":"26.117.29.236","CallStatus":0,"ID":2,"Name":"3","Sid":-1},
            //{"Status":0,"Vol":2,"Number":3,"WorkStatus":0,"IP":"26.117.36.128","CallStatus":0,"ID":3,"Name":"glr20190624001","Sid":-1}],
            //"Remark":"OK"}
            if (jsonReturn.getInteger("Ret") == 0) {
                com.alibaba.fastjson.JSONArray jsonArray = jsonReturn.getJSONArray("Terms");
                for (int i = 0; i < jsonArray.size(); i++) {
                    com.alibaba.fastjson.JSONObject job = jsonArray.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    //Status-1-离线 0-空闲>0-工作中
                    glrRadio.setRadioStatus(job.getInteger("Status"));
                    int valueRattop=job.getInteger("Vol");
                    //int valuePer=volumeConversionRattopToPer(valueRattop);
                    //glrRadio.setVol(valuePer);
                    glrRadio.setPhoneNumber(job.getString("Number"));
                    // WorkStatus
                    // #define WSTATE_IDLE         0       // 空闲
                    // #define WSTATE_SPEAK        1       // 寻呼讲话
                    // #define WSTATE_TALK         2       // 双向对讲
                    // #define WSTATE_LISTEN       3       // 收听寻呼
                    // #define WSTATE_MONITOR      6       // 终端监听
                    // #define WSTATE_ALARM        8       // 紧急报警广播
                    //glrRadio.settWorkStatus(job.getLong("WorkStatus"));
                    glrRadio.setIp(job.getString("IP"));
                    // CallStatus
                    // #define CSTATE_IDLE   0  // 空闲
                    // #define CSTATE_CONNECT  1  // 接通
                    // #define CSTATE_RING   2  // 振铃
                    // #define CSTATE_WAIT   3  // 等待
                    // #define CSTATE_HUNGUP  4  // 挂断
                    // #define CSTATE_BUSY   5  // 占线
                    // #define CSTATE_NOANSWER  6  // 无应答
                    // #define CSTATE_EMPTY  7  // 空号
                    // #define CSTATE_LIMITED  8  // 呼叫受限
                    // #define CSTATE_ERROR  9  // 连接错误
                    // #define CSTATE_FAILED  10  // 创建会话失败
                    // #define CSTATE_VERERR  11  // 版本错误
                    // #define CSTATE_SPKPROMPT 12  // 提示已接通
                    // #define CSTATE_SWITCH  13  // 呼叫切换
                    // #define CSTATE_WAIT_EX  0x83 // 对方忙时的呼叫等待
                    //glrRadio.settCallStatus(job.getLong("CallStatus"));
                    glrRadio.setSid(job.getString("Sid"));

                    //glrRadioMapper.updateById(glrRadio);
                }
            }else {
                throw new Exception("接口失败!");
            }
        }
    }

    @Override
    public void setRadioVol(GlrRadioTask domain) {
        if(StringUtil.isNotEmpty(domain.getIds())){
            String [] ids=domain.getIds().split(",");
            for(int i=0;i<ids.length;i++){
                if(StringUtil.isNotEmpty(ids[i])){
                    GlrRadioTask glrRadioTask = glrRadioTaskMapper.selectById(ids[i]);
                    List<String> memberIdsList = glrRadioTaskMapper.getMemberIdByTaskId(glrRadioTask.getId());
                    for (String memberId : memberIdsList) {
                        GlrRadio r = glrRadioMapper.selectById(memberId);
                        setRadioVol(r,domain.getVol());
                    }
                }
            }
        }
    }
    @Override
    public void setRadioVol(GlrRadio domain) {
        if(StringUtil.isNotEmpty(domain.getIds())){
            String [] ids=domain.getIds().split(",");
            for(int i=0;i<ids.length;i++){
                if(StringUtil.isNotEmpty(ids[i])){
                    GlrRadio r = glrRadioMapper.selectById(ids[i]);
                    setRadioVol(r,domain.getVol());
                }
            }
        }
    }

    public void setRadioVol(GlrRadio r,Integer vol){
        if (COMPANY_CODE_SPON.equals(r.getCompanyCode())){
            r.setVol(vol);
            Map<String, String> map = new HashMap<String, String>();
            if(vol>0){
                vol=(int)(vol*0.3);
                if(vol<1){
                    vol=1;
                }else if(vol>15){
                    vol=15;
                }
            }
            map.put("jsondata[terid]", r.getRadioId());
            map.put("jsondata[talkinv]", String.valueOf(vol));
            map.put("jsondata[talkoutv]", String.valueOf(vol));
            map.put("jsondata[bcinv]", String.valueOf(vol));
            map.put("jsondata[bcoutv]", String.valueOf(vol));
            com.alibaba.fastjson.JSONObject json = HttpRequestUtil.doPost(radio_teriocontrol, map, "UTF-8");
            if (json.getString("res").equals("1")) {
                glrRadioMapper.updateById(r);
            }
        }
        if (COMPANY_CODE_RATTOP.equals(r.getCompanyCode())){
            String stRadioId=r.getRadioId();
            String stRadioServerCode = r.getRadioServerCode();
            if (StringUtil.isNotEmpty(stRadioId) && StringUtil.isNotEmpty(stRadioServerCode)) {
                GlrRadioServer glrRadioServer=doGetByPropertyName("code", stRadioServerCode);
                r.setGlrRadioServer(glrRadioServer);
            }
            if (r.getGlrRadioServer() != null) {
                try{
                    int valuePer=vol;
                    int valueRattop=volumeConversionPerToRattop(valuePer);
                    JSONObject jsonParam = new JSONObject();

                    //jsonParam.put("TermIds", "[" + r.getRadioId() + "]");
                    JSONArray j=new JSONArray();
                    j.add(Long.parseLong(r.getRadioId()));
                    jsonParam.put("TermIds",j);

                    jsonParam.put("Volume", valueRattop);
                    com.alibaba.fastjson.JSONObject jsonReturn = IPCAST_FUNCTION(r.getGlrRadioServer() , "TermVolSet", jsonParam, true);
                    //{"Ret":0,"Remark":"OK"}
                    if (jsonReturn.getInteger("Ret") == 0) {
                        r.setVol(valuePer);
                        glrRadioMapper.updateById(r);
                    } else {
                        throw new Exception("接口失败!");
                    }
                }catch (Exception ex){

                }
            }
        }
    }

    public void delRattopFileId(String Sid){
        try{
            GlrRadioServer glrRadioServer=doGetByPropertyName("code", SERVER_CODE_RATTOP);
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("Sid", Long.parseLong(Sid));//终端 ID 列表
            com.alibaba.fastjson.JSONObject jsonReturn = IPCAST_FUNCTION(glrRadioServer, "FileSessionDestory", jsonParam, true);
            //{"Ret":0,"Remark":"OK"}
            if (jsonReturn.getInteger("Ret") == 0) {

            } else {
                throw new Exception("接口失败!");
            }
        }
        catch (Exception ex){
        }
    }
    public void delRattopMLId(Long MLId){
        try{
            GlrRadioServer glrRadioServer=doGetByPropertyName("code", SERVER_CODE_RATTOP);
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("ID", MLId);
            com.alibaba.fastjson.JSONObject jsonReturn = IPCAST_FUNCTION(glrRadioServer, "MLDelProg", jsonParam, true);
            //{"Ret":0,"Remark":"OK"}
            if (jsonReturn.getInteger("Ret") == 0) {

            } else {
                throw new Exception("接口失败!");
            }
        }
        catch (Exception ex){
        }
    }
    @Override
    public String getRattopFileId(String fileName){
        try{
            GlrRadioServer glrRadioServer=doGetByPropertyName("code", SERVER_CODE_RATTOP);
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("Type", 1);
            com.alibaba.fastjson.JSONObject jsonReturn = IPCAST_FUNCTION(glrRadioServer, "FileUpload", jsonParam, true);
            //{"Ret":0,"FtpPwd":"webcast","FtpUrl":"ftp://106.14.140.133:9002//f8826800932a11e9800200163e006137.mp3","FtpUsr":"websvr","FileId":"f8826800932a11e9800200163e006137","Remark":"OK"}
            if (jsonReturn.getInteger("Ret") == 0) {
                //String fileName = "C:\\test.mp3";
                Map<String, String> fileMap = new HashMap<String, String>();
                fileMap.put("userfile", fileName);
                FtpUtil ftpUtil = new FtpUtil();
                String stFtpUrl = jsonReturn.getString("FtpUrl");
                String[] aa = stFtpUrl.split("//");
                String[] bb = aa[1].split(":");
                FTPClient ftpClient;

                ftpClient = ftpUtil.getFTPClient(glrRadioServer.getIp(), jsonReturn.getString("FtpUsr"),
                        jsonReturn.getString("FtpPwd"), Integer.parseInt(bb[1]));
                ftpUtil.uploadFile(ftpClient, "/", aa[2], fileName);
                String stFileId=jsonReturn.getString("FileId");
                return stFileId;
            }
        }catch (Exception ex){

        }
        return "";
    }

    @Override
    public Long getRattopMediaId(String rattopFileId){
        try{
            GlrRadioServer glrRadioServer=doGetByPropertyName("code", SERVER_CODE_RATTOP);
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("ParentId", 0);
            jsonParam.put("Type", 1);
            jsonParam.put("Name", rattopFileId + ".mp3");
            jsonParam.put("FileId", rattopFileId);
            com.alibaba.fastjson.JSONObject jsonReturn = IPCAST_FUNCTION(glrRadioServer, "MLCreateNode", jsonParam, true);
            //{"Ret":0,"Length":129,"ID":5,"Remark":"OK"}
            if (jsonReturn.getInteger("Ret") == 0) {
                Long tMediaId = jsonReturn.getLong("ID");
                //Long tMediaLength = jsonReturn.getLong("Length");
                return tMediaId;
            } else {
                throw new Exception("接口失败!");
            }

        }catch (Exception ex){

        }
        return 0l;
    }

    /*
    @Override
    public void updateGlrRadioStatus(GlrRadio domain) throws Exception{
        GlrRadioServer glrRadioServer=doGetByPropertyName("code", SERVER_CODE_RATTOP);
        String stJSessionID = getRattopSessionId(glrRadioServer);
        updateGlrRadioStatus(domain,glrRadioServer,stJSessionID);
    }*/

    @Override
    public void updateGlrRadioStatus(GlrRadio domain,GlrRadioServer glrRadioServer,String stJSessionID) throws Exception
    {
        if (domain==null){
            return;
        }
        domain.setStatus(GLRConstant.RADIO_STATUS_OFFLINE);
        if(COMPANY_CODE_SPON.equals(domain.getCompanyCode())){
            Map<String,String> map = new HashMap<String,String>();
            map.put("jsondata[searchTxt]",domain.getRadioId());
            map.put("jsondata[onlyId]",domain.getRadioId());
            map.put("jsondata[groupName]","*");
            try{
                com.alibaba.fastjson.JSONObject json= HttpRequestUtil.doPost(HttpRequestUtil.PHP_GETSINGLETERMINALDATA_URL,map,"UTF-8");
                if(json.get("rows")!=null){
                    com.alibaba.fastjson.JSONObject jsonstr= (com.alibaba.fastjson.JSONObject) com.alibaba.fastjson.JSONObject.toJSON(json.getJSONArray("rows").get(0));
                    String status=jsonstr.getString("state");
                    //终端类型（-1：脱机； 0：XC 终端； 1：NAS 终端；2： SIP终端；3/4/5：APP 终端）
                    if("-1".equals(status)){
                        domain.setStatus(GLRConstant.RADIO_STATUS_OFFLINE);
                    }else{
                        String task=jsonstr.getString("task");
                        //终端状态（包含两种类型的值）0： 空闲；X1|X2|X3|X4|X5
                        //X1: (0：对讲 1： 监听； 2：广播 3： 会议）
                        //X2: (任务目标对应的终端 ID)
                        //X3: (0: 接收方 1：发起方)
                        //X4: (对应的任务名称）
                        //X5: (对应的播放列表名称, 如 test.list）
                        if("0".equals(task)){
                            domain.setStatus(GLRConstant.RADIO_STATUS_IDLE);
                        }else{
                            domain.setStatus(GLRConstant.RADIO_STATUS_WORKING);
                        }
                    }
                }else{
                    domain.setStatus(GLRConstant.RADIO_STATUS_OFFLINE);
                }
            }catch (Exception ex){
                domain.setStatus(GLRConstant.RADIO_STATUS_OFFLINE);
            }
        }
        if(COMPANY_CODE_RATTOP.equals(domain.getCompanyCode())){
            try {
                domain.setGlrRadioServer(glrRadioServer);
                if (domain.getGlrRadioServer()!=null){
                    doUpdateRattopTerminalInfo(domain,stJSessionID);
                    //Status-1-离线 0-空闲>0-工作中
                    if(domain.getRadioStatus()==-1){
                        domain.setStatus(GLRConstant.RADIO_STATUS_OFFLINE);
                    }
                    if(domain.getRadioStatus()==0){
                        domain.setStatus(GLRConstant.RADIO_STATUS_IDLE);
                    }
                    if(domain.getRadioStatus()>0){
                        domain.setStatus(GLRConstant.RADIO_STATUS_WORKING);
                    }
                    //glrRadioMapper.updateById(domain);
                }
            }catch(Exception ex) {
                ex.printStackTrace();
                domain.setStatus(GLRConstant.RADIO_STATUS_OFFLINE);
            }
        }
    }

    @Override
    public void doRattopTaskStartOrStop(GlrRadioTask domain,String status) throws Exception{
        //如果为雷拓
        if(COMPANY_CODE_RATTOP.equals(domain.getCompanyCode())){
            GlrRadioServer glrRadioServer=doGetByPropertyName("code", SERVER_CODE_RATTOP);
            domain.setGlrRadioServer(glrRadioServer);
            String taskId=domain.getTaskId();
            if (StringUtil.isNotEmpty(taskId)&&domain.getGlrRadioServer()!=null){
                //先停止任务
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("TaskID", Long.parseLong(taskId));
                com.alibaba.fastjson.JSONObject  jsonReturn = IPCAST_FUNCTION(domain.getGlrRadioServer(), "TaskManualStop", jsonParam, true);
                //{"Ret":0,"Remark":"OK"}
                if (jsonReturn.getInteger("Ret") == 0) {
                    domain.setStartStatus(GLRConstant.GLR_RADIO_TASK_STATUS_1);
                    domain.setStatus(GLRConstant.GLR_RADIO_TASK_STATUS_4);
                    glrRadioTaskMapper.updateById(domain);
                } else {
                    throw new Exception("接口失败!");
                }
            }

            List<String> st1List = new ArrayList<>();
            List<String> radioIdsList = glrRadioTaskMapper.getRadioIdByTaskId(domain.getId());
            st1List = new ArrayList<>();
            for (String id : radioIdsList) {
                st1List.add(id);
            }
            String radioIds = StringUtil.listToString(st1List, ',');

            List<Map<String, Object>> fieldsList =glrRadioTaskMapper.getFieldsByTaskId(domain.getId());
            st1List = new ArrayList<>();
            for (Map<String, Object> o : fieldsList) {
                st1List.add(o.get("rattop_media_id").toString());
            }

            String mediaIds = StringUtil.listToString(st1List, ',');

            JSONObject jsonParam = new JSONObject();

            jsonParam.put("Type", 1);//1–每天任务 2– 每周任务3– 每月任务 4-一次性任务

            JSONObject dayItemParam = new JSONObject();
            dayItemParam.put("Every",1);
            jsonParam.put("DayItem", dayItemParam);//对每天任务有效 EveryDay 对象
            int playVol=domain.getPlayVol();
            int playRattopVol=volumeConversionPerToRattop(playVol);
            jsonParam.put("PlayVol",playRattopVol);

            //jsonParam.put("Tids", "[" + radioIds + "]");
            JSONArray j91=new JSONArray();
            j91.add(Long.parseLong(radioIds));
            jsonParam.put("Tids",j91);

            jsonParam.put("PlayMode", 0); //0-顺序 1-随机

            Integer playTime = domain.getPlayTime();
            if (playTime==null) {
                playTime =0;
            }
            if (playTime>0){
                playTime=playTime*60;//以分钟为单位了
                jsonParam.put("Length", playTime);  //播放时长
            }

            jsonParam.put("StartTime", domain.getStartTime()+" "+domain.getDivision()+":00");  //yyyy-mm-dd hh:mm:ss
            jsonParam.put("EndDate", domain.getEndTime());  //yyyy-mm-dd，可以没有本字段
            if (GLRConstant.GLR_RADIO_TASK_STATUS_0.equals(status)){
                jsonParam.put("Status", 1); //0-停止 1-运行
                jsonParam.put("Enable", 1); //0-冻结任务 1-启用任务
            }
            if (GLRConstant.GLR_RADIO_TASK_STATUS_1.equals(status)){
                jsonParam.put("Status", 0);
                jsonParam.put("Enable", 0);
            }

            //jsonParam.put("ProgIds", "[" + mediaIds + "]");
            JSONArray j99=new JSONArray();
            j99.add(Long.parseLong(mediaIds));
            jsonParam.put("ProgIds",j99);

            String nowday_user = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "_"
                    + SysUtil.getUserInfo().getUsername();
            jsonParam.put("Name", domain.getName() + nowday_user);

            String stFunction="";
            if (StringUtil.isNotEmpty(domain.getTaskId())) {
                stFunction="TaskUpdate";
                jsonParam.put("ID", Long.parseLong(domain.getTaskId()));//  -1 代表新建任务
            }else {
                stFunction="TaskCreate";
                jsonParam.put("ID", -1);//  -1 代表新建任务
            }

            JSONObject jsonParam1 = new JSONObject();
            jsonParam1.put("Item", jsonParam);

            com.alibaba.fastjson.JSONObject  jsonReturn = IPCAST_FUNCTION(domain.getGlrRadioServer(), stFunction, jsonParam1, true);
            //{"Ret":0,"TaskID":2,"Remark":"OK"}
            if (jsonReturn.getInteger("Ret") == 0) {
                String tTaskID = jsonReturn.getString("TaskID");
                if (StringUtil.isNotEmpty(tTaskID)){
                    domain.setTaskId(tTaskID);
                }
                if (GLRConstant.GLR_RADIO_TASK_STATUS_0.equals(status)){
                    domain.setStatus(GLRConstant.GLR_RADIO_TASK_STATUS_0);
                    domain.setStartStatus(GLRConstant.GLR_RADIO_TASK_STATUS_4);
                }
                if (GLRConstant.GLR_RADIO_TASK_STATUS_1.equals(status)){
                    domain.setStatus(GLRConstant.GLR_RADIO_TASK_STATUS_1);
                    domain.setStartStatus(GLRConstant.GLR_RADIO_TASK_STATUS_4);
                }
                glrRadioTaskMapper.updateById(domain);
            } else {
                throw new Exception("接口失败!");
            }
        }
    }

    @Override
    public void doRattopTaskRunningOrNot(GlrRadioTask domain,String status) throws Exception{
        //如果为雷拓
        if(COMPANY_CODE_RATTOP.equals(domain.getCompanyCode())) {
            GlrRadioServer glrRadioServer = doGetByPropertyName("code", SERVER_CODE_RATTOP);
            domain.setGlrRadioServer(glrRadioServer);
            String taskId = domain.getTaskId();
            if (StringUtil.isNotEmpty(taskId) && domain.getGlrRadioServer() != null) {
                JSONObject jsonParam = new JSONObject();
                jsonParam.put("TaskID", Long.parseLong(taskId));

                String stFunction="";
                if (GLR_RADIO_TASK_STATUS_3.equals(status)){
                    stFunction="TaskManualStart";
                }
                if (GLR_RADIO_TASK_STATUS_4.equals(status)){
                    stFunction="TaskManualStop";
                }

                com.alibaba.fastjson.JSONObject  jsonReturn = IPCAST_FUNCTION(domain.getGlrRadioServer(), stFunction, jsonParam, true);
                //{"Ret":0,"Remark":"OK"}
                if (jsonReturn.getInteger("Ret") == 0) {
                    if (GLR_RADIO_TASK_STATUS_3.equals(status)){
                        domain.setStartStatus(GLR_RADIO_TASK_STATUS_3);
                    }
                    if (GLR_RADIO_TASK_STATUS_4.equals(status)){
                        domain.setStartStatus(GLR_RADIO_TASK_STATUS_4);
                    }
                    glrRadioTaskMapper.updateById(domain);
                } else {
                    throw new Exception("接口失败!");
                }
            }
        }
    }

    @Override
    public Boolean deleteRadioTask(GlrRadioTask domain)throws Exception{
        //如果为雷拓
        if(COMPANY_CODE_RATTOP.equals(domain.getCompanyCode())) {
            GlrRadioServer glrRadioServer = doGetByPropertyName("code", SERVER_CODE_RATTOP);
            domain.setGlrRadioServer(glrRadioServer);
            Long tTaskID = Long.parseLong(domain.getTaskId());
            if (tTaskID > 0 && StringUtil.isNotEmpty(tTaskID) && domain.getGlrRadioServer() != null) {

                //立刻停止
                doRattopTaskRunningOrNot(domain,GLR_RADIO_TASK_STATUS_4);

                //任务停用
                doRattopTaskStartOrStop(domain,GLR_RADIO_TASK_STATUS_1);

                JSONObject jsonParam = new JSONObject();
                jsonParam.put("TaskID", tTaskID);
                com.alibaba.fastjson.JSONObject  jsonReturn = IPCAST_FUNCTION(domain.getGlrRadioServer(), "TaskDelete", jsonParam, true);
                //{"Ret":0,"Remark":"OK"}
                if (jsonReturn.getInteger("Ret") == 0) {
                    //domain.setTaskId("0L");
                    //glrRadioTaskMapper.updateById(domain);
                    return true;
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public List<GlrRadioTask> doRattopTaskList(String ids) throws Exception{
        List<String> idList=Arrays.asList(ids.split(","));
        List<GlrRadioTask> glrRadioTaskList=new ArrayList<>();
        for(String taskId:idList) {
            GlrRadioTask domain = glrRadioTaskMapper.selectById(taskId);
            if (domain != null) {
                //如果为雷拓
                if(COMPANY_CODE_RATTOP.equals(domain.getCompanyCode())) {
                    if (StringUtil.isNotEmpty(domain.getTaskId())){
                        GlrRadioServer glrRadioServer = doGetByPropertyName("code", SERVER_CODE_RATTOP);
                        domain.setGlrRadioServer(glrRadioServer);
                        JSONObject jsonParam = new JSONObject();

                        //jsonParam.put("TaskIDs", "["+domain.getTaskId()+"]");//终端 ID 列表
                        JSONArray j=new JSONArray();
                        j.add(Long.parseLong(domain.getTaskId()));
                        jsonParam.put("TaskIDs",j);

                        com.alibaba.fastjson.JSONObject jsonReturn = IPCAST_FUNCTION(domain.getGlrRadioServer(),"TaskList", jsonParam, true);
                        //{"Ret":0,"Items":[
                        //{"Status":0,"Type":4,"PlayVol":2,"Tids":[2,1,3],"PlayMode":1,"RepeatTime":1,"StartTime":"2019-06-27 14:53:49",
                        //"Enable":1,"ProgIds":[5,16,7,9],"ID":1,"PrePower":2,"Name":"ttttt"}
                        //],"Remark":"OK"}
                        if (jsonReturn.getInteger("Ret") == 0) {
                            com.alibaba.fastjson.JSONArray jsonArray = jsonReturn.getJSONArray("Items");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                com.alibaba.fastjson.JSONObject job = jsonArray.getJSONObject(i);
                                Long Status=job.getLong("Status");//0-停止 1-运行
                                Long Enable=job.getLong("Enable");//0-冻结 1-启用
                                GlrRadioTask g=new GlrRadioTask();
                                if (Enable==1) g.setStatuSwitch0(true);
                                else g.setStatuSwitch0(false);
                                if (Status==1) g.setStatuSwitch1(true);
                                else g.setStatuSwitch1(false);
                                g.setId(taskId);
                                glrRadioTaskList.add(g);
                            }
                        }
                    }
                }
            }
        }
        return glrRadioTaskList;
    }

    @Override
    public List<GlrRadioTask> getRattopTermState(String ids) throws Exception{
        List<String> idList=Arrays.asList(ids.split(","));
        List<GlrRadioTask> glrRadioTaskList=new ArrayList<>();
        for(String taskId:idList) {
            GlrRadioTask domain = glrRadioTaskMapper.selectById(taskId);
            if (domain != null) {
                //如果为雷拓
                if(COMPANY_CODE_RATTOP.equals(domain.getCompanyCode())) {
                    if (StringUtil.isNotEmpty(domain.getTaskId())){
                        GlrRadioServer glrRadioServer = doGetByPropertyName("code", SERVER_CODE_RATTOP);
                        domain.setGlrRadioServer(glrRadioServer);
                        JSONObject jsonParam = new JSONObject();

                        //jsonParam.put("TermIDs", "["+domain.getTaskId()+"]");//终端 ID 列表
                        JSONArray j=new JSONArray();
                        j.add(Long.parseLong(domain.getTaskId()));
                        jsonParam.put("TermIDs",j);

                        com.alibaba.fastjson.JSONObject jsonReturn = IPCAST_FUNCTION(domain.getGlrRadioServer(),"getTermState", jsonParam, true);
                        //Status-1-离线 0-空闲>0-工作中
                        //{"Ret":0,"Terms":[
                        //{"Status":-1,"Vol":2,"Number":1,"WorkStatus":0,"IP":"26.117.13.188","CallStatus":0,"ID":1,"Name":"glr20190617001","Sid":-1},
                        //{"Status":-1,"Vol":2,"Number":2,"WorkStatus":0,"IP":"26.117.29.236","CallStatus":0,"ID":2,"Name":"3","Sid":-1},
                        //{"Status":0,"Vol":2,"Number":3,"WorkStatus":0,"IP":"26.117.36.128","CallStatus":0,"ID":3,"Name":"glr20190624001","Sid":-1}],
                        //"Remark":"OK"}
                        if (jsonReturn.getInteger("Ret") == 0) {
                            com.alibaba.fastjson.JSONArray jsonArray = jsonReturn.getJSONArray("Terms");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                com.alibaba.fastjson.JSONObject job = jsonArray.getJSONObject(i);
                                Long Status=job.getLong("Status");//-1-离线 0-空闲>0-工作中
                                GlrRadioTask g=new GlrRadioTask();
                                if (Status==0||Status==-1) g.setStatuSwitch1(false);
                                else g.setStatuSwitch1(false);
                                g.setId(taskId);
                                glrRadioTaskList.add(g);
                            }
                        }
                    }
                }
            }
        }
        return glrRadioTaskList;
    }

}
